$(document).ready(function(){
	
	// variables
	var xmlUrl = "xml/eurofxref-hist-90d.xml";
	var synchronously = false;
	
	// Default view when load the page
	loadTemplate('includes/home.html', 'home');
	
	// Get the database object
	db = saveXMLinMemory(xmlUrl, synchronously);
	
	// On refresh the page
	$(window).bind('beforeunload',function(){
	});
	
	// Back and Forward Browser buttons control
	$(window).bind("popstate", function () {
//		$.getScript(location.href);
	});
	  
	
	$("#logo").click(function(){
		loadTemplate('includes/home.html', 'home');
		return false;
	});
	$("#btnExchange").click(function(){
		loadTemplate('includes/exchange.html', 'exchange');
		loadSelectOptions(db);
		return false;
    });
	$("#btnHistory").click(function(){
		loadTemplate('includes/history.html', 'history');
		return false;
	});
	
	// exchange.html (on currency exchange page)
		$("body").on('click', "#btnChange", function() {
			var amount = $("#amount").val();
			var message = "";
			if($.isNumeric(amount)){
				var currency_in = $("#cur_in option:selected").val();
				var currency_out= $("#cur_out option:selected").val();
				message = changeCalculator(db, amount, currency_in, currency_out);
			}else{
				alert("A number is required");
			}
			$("#result").html(message);
		});
		
		$("body").on('click', "#btnReload", function() {
			db = saveXMLinMemory(xmlUrl, synchronously);
		});
	
});

function loadTemplate(url,title) {
	var info = "lang=" + $('html').attr('lang');
	var link = title;
	$.getScript(this.href);
	history.pushState(null, "", "index.html#"+link);
	$.ajax({
        async: false,
        cache: false,
		url: url,
		type: "GET",
		data: info,
		success: function(info){
			$("#content").html(info);
		}
	});
}

/**
 * Open and save the xml file values
 * @returns object
 */
function saveXMLinMemory(url, synchronously){
	delete db;
	// create database in-memory using www.taffydb.com
	var db = TAFFY();

	if (window.XMLHttpRequest) {
		// new browsers which implemented XMLHttpRequest object
		xhttp=new XMLHttpRequest();
	} else {
		// Old browsers, like IE5 and IE6, which uses ActiveX
		xhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
//    xhttp.open("GET","http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml",true);
    xhttp.open("GET",url, synchronously);
    xhttp.send();

    step1= xhttp.responseXML.childNodes;
    length1 = step1.length;
    
    // Parent tags have the same name than children, so my solution are this FOR loops
    for(i=0; i<length1; i++){
    	step2 = step1[i].childNodes;
    	length2 = step2.length;
    	
    	for(j=0; j<length2; j++){
			if(step2[j].nodeName=="Cube"){
				step3 = step2[j].childNodes;
				length3 = step3.length;
				
				for(h=0; h<length3; h++){
					step4 = step3[h].childNodes;
					try {
					    var dateday = step3[h].getAttribute('time');
					    length4 = step4.length;

						for(k=0; k < length4; k++){
							var currency = step4[k].getAttribute('currency');
							var rate = step4[k].getAttribute('rate');

							db.insert({date: dateday, currency: currency, rate: rate});
						}
					} catch(e){ 
						// We don't need this exception value 
					}
				}
			}
		}
	}
	// show each row
	// db().limit(10).each(function (r) {console.log(r.date + r.currency + r.rate);});
    return db;
}

function loadSelectOptions(db){
	var currencies = db().distinct("currency");
	for(var i in currencies){
		$("#cur_in").append("<option value="+currencies[i]+">"+currencies[i]+"</option>");
		$("#cur_out").append("<option value="+currencies[i]+">"+currencies[i]+"</option>");
	}
}

function changeCalculator(db, amount, currency_in, currency_out){
	var lastdate = "";
	var rate_in  = "";
	var rate_out = "";
	var result   = "";
	
	// If checked currency is euro, is not in the XML, so we set the value manually
	if(currency_in === "EUR"){	rate_in = 1;	}
	if(currency_out === "EUR"){	rate_out = 1;	}

	// Now, we order our data to get the last/newest date
	db().order("date desc").limit(1).each(function(r){
		lastdate = r.date;
	});
	
	// And now, we load just the last/newest date rates
	db({date:lastdate}).each(function(r){
		if(r.currency === currency_in){
			rate_in = r.rate;
		}
		if(r.currency === currency_out){
			rate_out = r.rate;
		}
	});
	
	// After check if the rates are correct, we proceed to get the exchanged amount
	if($.isNumeric(rate_in) && $.isNumeric(rate_out)){
		result = changeCalculatorAlgorithm(amount, rate_in, rate_out);
	}else{
		alert("Error extracting rates");
	}
	var message = "<h1>" + amount + " " + currency_in + " = " + result + " " + currency_out + " (" + lastdate + ")</h1>";
	return message;
}

function changeCalculatorAlgorithm(amount, rate_in, rate_out){
	// Save the amount to change in euro currency, because rates are based on how much is 1 euro
	amount_in_euro = rate_in * amount;

	// And just return the amount in euro currency parsed to the out currency's rate.
	result = rate_out * amount_in_euro;
	
	// Finally, we return the result rounded to 2 decimals (even if there are not decimals)
	return result.toFixed(2);
}